var myApp = angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
    $routeProvider
    .when('/user/all', {
        templateUrl: 'template-users.html',
        controller: 'usersController',
        activeSideTab: 'user'
    })
    .when('/admin/all', {
        templateUrl: 'template-admin-all.html',
        controller: 'adminsController',
        activeSideTab: 'admin'
    })
    .when('/admin/add', {
        templateUrl: 'template-admin-add.html',
        controller: 'adminAddController',
        activeSideTab: 'admin'
    })
    .when('/admin/detail/:id', {
        templateUrl: 'template-admin-detail.html',
        controller: 'adminDetailController',
        activeSideTab: 'admin'
    })
    .when('/business', {
        templateUrl: 'template-business.html',
        controller: 'businessController',
        activeSideTab: 'type'
    })
    .when('/user/:user_id', {
        templateUrl: 'template-user-detail.html',
        controller: 'userDetailController',
        activeSideTab: 'user'
    })
    .when('/overview', {
        templateUrl: 'template-overview.html',
        controller: 'overviewController',
        activeSideTab: 'overview'
    })
    .when('/publish', {
    	templateUrl: 'template-publish.html',
    	controller: 'publishController',
        activeSideTab: 'publish'
    })
    .when('/blog/add', {
        templateUrl: 'template-blog-add.html',
        controller: 'blogAddController',
        activeSideTab: 'publish'
    })
    .when('/blog/edit/:id', {
        templateUrl: 'template-blog-add.html',
        controller: 'blogEditController',
        activeSideTab: 'publish'
    })
    .when('/blog/detail/:id', {
        templateUrl: 'template-blog-detail.html',
        controller: 'blogDetailController',
        activeSideTab: 'publish'
    })
    .when('/account', {
    	templateUrl: 'template-account.html',
    	controller: 'accountController',
        activeSideTab: 'account'
    })
    .when('/blog/slides',{
        templateUrl: 'template-blog-slides.html',
        controller: 'blogSlidesController',
        activeSlideTab: 'publish'
    })
    .when('/help',{
        templateUrl: 'template-help.html',
        controller: 'helpController',
        activeSlideTab: 'help'
    })
    .otherwise({redirectTo: '/user/all'});
}]);


myApp.controller('usersController', ['$scope', '$location', '$http', function($scope, $location, $http) {

    $scope.go = function(hash){
        $location.path(hash);
    };

    $scope.userTypeList = globalData.userTypeList;

    var queryStrOrigin = {
        username: '',
        realname: '',
        phone: '',
        email: '',
        typeid: 0,  // 0: 默认为全部类型，也就是大众用户A类
        area: '',
        rStartTime: '',
        rEndTime: moment().format('YYYY-MM-DD'),
        lStartTime: '',
        lEndTime: moment().format('YYYY-MM-DD'),
        order: ''
    };

    var queryStr = _.extend({}, queryStrOrigin);

    $scope.queryStr = queryStr;

    // 分页模型
    var pagination = {
        all: 0,
        index: 1,
        limit: 10,
        pageCount: function(){
            return Math.ceil( this.all / this.limit );
        },
        pageArr: function(){
            var page = this.index;
            var pageCount = Math.ceil( this.all / this.limit );
            var p1 = page-2; if( p1 < 1){ p1=1; } var p2=page+2; if(p2>pageCount){p2=pageCount;}
            var arr = [];
            for (var i = p1; i <= p2; i++) {
                arr.push(i);
            }

            return arr;
        }
    };

    $scope.pagination = pagination;

    // 分页跳转工具
    var pageTo = function(page, limit){
        pagination.index = page  || pagination.index;
        pagination.limit = limit || pagination.limit;

        var params = _.extend({
                limit: pagination.limit,
                page: pagination.index
            }, queryStr);

        params = _.pick(params, function(value, key, object) {
          return !!value;
        });

        if(params.rStartTime){
            params.rStartTime = moment(params.rStartTime).format('YYYY-MM-DD HH:mm:ss');
        }

        if(params.rEndTime){
            params.rEndTime = moment(params.rEndTime).format('YYYY-MM-DD HH:mm:ss');
        }

        if(params.lStartTime){
            params.lStartTime = moment(params.lStartTime).format('YYYY-MM-DD HH:mm:ss');
        }

        if (params.lEndTime){
            params.lEndTime = moment(params.lEndTime).format('YYYY-MM-DD HH:mm:ss');
        }

        $http({
            url: '/rest/user',
            method: 'get',
            params: params
        })
        .success(function(msg){
            if (msg.error) {
                
            }else{
                $scope.userList = msg.data;
                pagination.all = msg.all;
            }
        });
    };

    $scope.pageTo = pageTo;

    $scope.selectPrevious = function(){
        pageTo(pagination.index-1);
    };

    $scope.selectNext = function(){
        pageTo(pagination.index+1);
    };

    // 初始化一下
    pageTo();

    $scope.search = function(){
        pageTo(1);
    };

    $scope.deleteUser = function(uid, $event){
        $event.stopPropagation();

        if (confirm('确定要删除用户 '+ uid +'？')) {
            $http.delete('/rest/user/'+uid).success(function(msg){
                if (msg.error) {

                }else{
                    iosOverlay({
                      text: "删除成功！",
                      duration: 500,
                      icon: '<i class="fa fa-check"></i>',
                      onhide: pageTo
                    });
                    
                }
            });
        }
    };

    // 重置表单，并重新加载
    // 可以留意这里体现出的JS“值传递”特性
    $scope.reset = function(){
        queryStr = _.extend({}, queryStrOrigin);
        $scope.queryStr = queryStr;
        pageTo();
    };

}])

.controller('userDetailController', ['$scope', '$location', '$http', '$routeParams', function($scope, $location, $http, $routeParams){
    var user_id = $routeParams.user_id;

    $scope.typeListAll = [{
        id: 3,
        name: 'B类'
    }, {
        id: 2,
        name: 'C类'
    }];

    $scope.ifShowAddTypeView = false;

    var getUserInfo = function(){
        $http.get('/rest/user/'+user_id)
        .success(function(msg){
            if (msg.error) {
                
            }else{
                $scope.userinfo = msg.info;
                $scope.typeList = msg.type;

                var lastLoginTime = msg.info.logintime;

                $scope.loginInfo = {
                    lastLoginTime: lastLoginTime ? moment(lastLoginTime).format('YYYY-MM-DD HH:mm:ss') : '暂无记录',
                    fromNow: lastLoginTime ? moment(lastLoginTime).fromNow() : ''
                };
            }
        });
    };

    getUserInfo();

    // 更新用户信息
    $scope.updateUserInfo = function(uid){
        $http.put('/rest/user/info', $scope.userinfo)
        .success(function(msg){
            if (msg.error) {
                
            }else{
                iosOverlay({
                  text: "修改成功！",
                  duration: 500,
                  icon: '<i class="fa fa-check"></i>'
                });
            }
        });
    };

    $scope.deleteUser = function(){
        if (confirm('确定要删除此用户？')) {
            $http.delete('/rest/user/'+user_id)
            .success(function(msg){
                if (msg.error) {
                    
                }else{
                    $location.path('/user/all');
                }
            });
        }
    };

    $scope.addTypeForUser = function(){
        var data = {
            userid: user_id,
            typeid: $scope.newType
        };


        if (data.typeid!= '') {
            $http.post('/rest/user/type', data).success(function(msg){
                if (msg.error) {

                }else{
                    iosOverlay({
                      text: "业务添加成功！",
                      duration: 500,
                      icon: '<i class="fa fa-check"></i>'
                    });

                    getUserInfo();
                    $scope.ifShowAddTypeView=false;
                }
            });
        }else{

        }
    };

    $scope.deleteTypeForUser = function(typeid){
        if (typeid==1) {
            iosOverlay({
              text: "不能删除A类业务",
              duration: 500,
              icon: '<i class="fa fa-times"></i>'
            });
        }else{
            $http.delete('/rest/user/type?userid=' + user_id + '&typeid=' + typeid)
            .success(function(msg){
                if (msg.error) {
                    iosOverlay({
                        icon: '<i class="fa fa-times"></i>',
                        text: msg.description,
                        duration: 800
                    });
                }else{
                    iosOverlay({
                        icon: '<i class="fa fa-check"></i>',
                        text: '删除成功！',
                        duration: 500
                    });
                    getUserInfo();
                }
            });
        }
    };

    $scope.signInLogs = globalData.signInLogs;

    $scope.authorities = globalData.authorities;

    $scope.genderMap = [{
        value: 0,
        text: '未知'
    }, {
        value: 1,
        text: '男'
    }, {
        value: 2,
        text: '女'
    }];

}])

.controller('adminsController', ['$scope', '$http', '$location', function($scope, $http, $location) {
    $scope.authorities = globalData.authorities;

    $scope.go = function(hash){
        $location.path(hash);
    };

    $http({
        url: '/rest/admin',
        method: 'get',
        params: {
            limit: 50,
            page : 1
        }
    })
    .success(function(msg){
        if (msg.error) {
            
        }else{
            $scope.userList = msg.data;
            $scope.all = msg.all;
        }
    });

    $scope.deleteAdmin = function(adminid, $event){
        $event.stopPropagation();

    };
}])

.controller('adminAddController', function($scope, $http) {
    $scope.newAdmin = {
        username: '',
        password: '',
        typecode: 0
    };

    $scope.submitAdd = function(){
        $http.post('/rest/admin', $scope.newAdmin)
        .success(function(msg){
            if(msg.error){

            }else{
                iosOverlay({
                    icon: '<i class="fa fa-check"></i>',
                    text: '添加成功！',
                    duration: 500
                });
            }
        });
    };
})

.controller('adminDetailController', ['$scope', '$location', '$http', '$routeParams', function($scope, $location, $http, $routeParams){
    var adminId = $routeParams.id;

    $scope.authorities = globalData.authorities;

    $http({
        url: '/rest/admin/' + adminId,
        method: 'get'
    })
    .success(function(msg){
        if (msg.error) {
            
        }else{
            $scope.admin = msg;
        }
    });


    $scope.onChange = function(){
        $scope.admin.typecode = parseInt($scope.admin.typecode);

        $http.put('/rest/admin/' + adminId, $scope.admin)
        .success(function(msg){
            if (msg.error) {
                iosOverlay({
                    icon: '<i class="fa fa-times"></i>',
                    text: msg.description,
                    duration: 800
                });
            }else{
                iosOverlay({
                    icon: '<i class="fa fa-check"></i>',
                    text: '权限修改成功！',
                    duration: 500
                });
            }
        });
    };

    $scope.deleteAdmin = function(){
        $http.delete('/admin/' + adminId + '?typecode=' + $scope.admin.typecode)
        .success(function(msg){
            if (msg.error) {
                iosOverlay({
                    icon: '<i class="fa fa-times"></i>',
                    text: msg.description,
                    duration: 800
                });
            }else{
                iosOverlay({
                    icon: '<i class="fa fa-check"></i>',
                    text: '删除成功！',
                    duration: 500
                });
                $location.path('/admin/all/');
            }
        });
    }
}])

.controller('businessController', ['$scope', '$location', '$http', '$routeParams', function($scope, $location, $http, $routeParams){
    $scope.editing = false;

    function getList(){
        $http.get('/rest/type')
        .success(function(msg){
            if (msg.error) {

            }else{
                $scope.typeList = msg.data;
                $scope.typeCount = msg.all;
            }
        });
    };

    getList();
    $scope.getList = getList;

    $scope.newType = {
        pid: 0,
        typename: '',
        remark: ''
    };

    $scope.getType = function(typeid){
        $http.get('/rest/type/'+typeid)
        .success(function(msg){
            if (msg.error) {

            }else{
                $scope.selected = msg;
            }
        });
    };

    $scope.saveType = function(typeid){
        if(!$scope.selected.pid){
            $scope.selected.pid = 0;
        }

        $http.put('/rest/type/'+typeid, $scope.selected)
        .success(function(msg){
            if (msg.error) {

            }else{
                iosOverlay({
                    icon: '<i class="fa fa-check"></i>',
                    text: '保存成功！',
                    duration: 500,
                    onhide: getList
                });
            }
        });
    };
}])

.controller('overviewController', function($scope) { 

    $('#highcharts-user-count').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            height: 300
        },
        title: {
            text: '用户活跃度统计'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                }
            }
        },
        series: [{
            type: 'pie',
            name: '用户活跃度统计',
            data: [
                ['活跃用户',       26.8],
                ['不活跃用户',   45.0],
                {
                    name: '重度用户',
                    y: 12.8,
                    sliced: true,
                    selected: true
                }
            ]
        }]
    });

    $('#highcharts-daily-active-users').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: '网站用户数量统计'
        },
        subtitle: {
            text: '数据来源: 播发系统内部统计'
        },
        xAxis: {
            labels: {
                formatter: function() {
                    return this.value; // clean, unformatted number for year
                }
            }
        },
        yAxis: {
            title: {
                text: '人数'
            },
            labels: {
                formatter: function() {
                    return this.value / 1000 +'k';
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name}  <b>{point.y:,.0f}</b>'
        },
        plotOptions: {
            area: {
                pointStart: 1940,
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            name: '活跃用户',
            data: [null, null, null, null, null, 6 , 11, 32, 110, 235, 369, 640,1005, 1436,
                    2063, 3057, 4618, 6444, 9822, 10468, 11434, 12126,13387, 14459, 15056, 16982,
                    19040, 31233, 29224, 27342, 26662,26956, 27912, 28999, 28965, 27826, 25579,
                    25722, 24826, 24605,24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344,
                    23586,22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950,
                10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104 
            ]
        }, {
            name: '总注册用户数',
            data: [0, 10, 200, 300, 500, 600, 800 , 900 , 1007 ,1300, 1544, 2544, 5500,
                6800, 7500, 8200, 9426, 10660, 11869, 12060, 13605, 14471, 15322, 16438, 17521, 18619,
                19089, 20339, 21499, 22438, 23435, 24892, 25345, 26315, 27985, 28955, 29205,
                30044, 31393, 32935, 33062, 34049,35552, 36804, 37431, 38197, 45000, 43000,
                41000, 39000, 37000,35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000,
                22000,21000, 20000, 19000, 18000, 18000, 17000, 16000
            ]
        }]
    });
})

.controller('publishController', ['$scope', '$http', function($scope, $http) {
    
    $http({
        url: '/rest/blog',
        method: 'get',
        params: {
            limit: 10,
            page: 1
        }
    })
    .success(function(msg){
        if (msg.error) {
            
        }else{
            $scope.articleList = msg.data;
        }
    });
}])

.controller('blogAddController', ['$scope', '$routeParams', '$http', '$location',
  function($scope, $routeParams, $http, $location){
    $scope.back = '#/publish';

    $("#epiceditor-content").markdown({autofocus:false,savable:false});

    $scope.blog = {
        author: '',
        title: '',
        content: '',
        type: 1,
        state: 0
    };

    $scope.submitPost = function(){
        var content = $("#epiceditor-content").val();
        $scope.blog.content = content;

        $http.post('/rest/blog', $scope.blog).success(function(msg){
            if(msg.error){

            }else{                
                iosOverlay({
                  text: "添加成功！",
                  duration: 800,
                  icon: '<i class="fa fa-check"></i>'
                });
                $location.path('/blog/detail/'+ msg.id);
            }
        });
    };
}])

.controller('blogEditController', ['$scope', '$routeParams', '$http', '$location',
  function($scope, $routeParams, $http, $location){
    var id = $routeParams.id;
    $scope.back = '#/blog/detail/'+id;

    $("#epiceditor-content").markdown({autofocus:false,savable:false});

    $http({
        url: '/rest/blog/'+id,
        method: 'get'
    })
    .success(function(msg){
        if (msg.error) {
            
        }else{
            $scope.blog = msg;
            $("#epiceditor-content").val(msg.content);
        }
    });

    // 提交修改
    $scope.submitPost = function(){
        var content = $("#epiceditor-content").val();
        $scope.blog.content = content;

        $http.put('/rest/blog', $scope.blog).success(function(msg){
            if(msg.error){

            }else{
                $location.path('/blog/detail/'+id);
                iosOverlay({
                  text: "修改成功！",
                  duration: 800,
                  icon: '<i class="fa fa-check"></i>',
                  onhide: function(){
                    
                  }
                });
            }
        });
    };
    
}])

.controller('blogDetailController', ['$scope', '$routeParams', '$http', '$location',
    function($scope, $routeParams, $http, $location){
    var id = $routeParams.id;
    $http({
        url: '/rest/blog/'+id,
        method: 'get'
    })
    .success(function(msg){
        if (msg.error) {
            
        }else{
            $scope.blog = msg;
            $scope.blog.contentHTML = markdown.toHTML(msg.content);
            $('#blog-detail-content').html($scope.blog.contentHTML);
        }
    });

    $scope.deleteArticle = function(id){
        if(confirm('确定要删除这篇文章吗？')){
            $http.delete('/rest/blog/'+id)
            .success(function(msg){
                if(msg.error){

                }else{
                    iosOverlay({
                      text: "删除成功！",
                      duration: 800,
                      icon: '<i class="fa fa-check"></i>'
                    });
                    $location.path('/publish');
                }
            });
        }
    }
}])

.controller('accountController', ['$scope', '$http', function($scope, $http) {
    var pass = {
        present: '',
        willuse: ''
    };

    $scope.pass = pass;

    var hint = {
        error: false,
        text: ''
    };

    $scope.hint = hint;

    $scope.updatePass = function(){
        $http.put('/account/password', pass)
        .success(function(msg){
            if(msg.error){
                hint.error = true;
                hint.text  = msg.description || msg.error;
            }else{
                iosOverlay({
                  text: "密码修改成功！",
                  duration: 600,
                  icon: '<i class="fa fa-check"></i>'
                });
                hint.error = false;
            }
        });
    };
}])

.controller('sidenavController', function($scope, $route){
    $scope.$route = $route;
	// $scope.active = function(target){
	// 	$(target).parent().find('.active').removeClass('active');
	// 	$(target).addClass('active');
	// };
})

.controller('blogSlidesController', function($scope, fileReader){
    $scope.carouselshow = true;
    var index = -1;

    //carousel
    var slides = $scope.slides = [];
    var pushSlides = function(id){
        var active;
        if(id==0){
            active = 'active';
        }else{
            active = '';
        }
        var newWidth = slides.length + 1;
        slides.push({
          image: '/img/a-' + newWidth + '.jpg',
          index: id,
          active: active
        });
    };

    for(var i = 0; i < 6; i++){
        pushSlides(i);
    }  


    //interval carousel
    $('#carouselid').carousel({
      interval: 2000
    })

    //clear input -type- text
    $scope.inputClear = function(){
        $scope.imageSrc = "";
        $scope.carouselshow = true;
    }

    $scope.submitPic = function(){
        $scope.carouselshow = true;

        if($scope.imageSrc != undefined && $scope.imageSrc != ""){
            slides.push({
              image: $scope.imageSrc,
              index: slides.length,
              active:''
            });     
        };
    }

    $scope.choosePic = function(){
        $("#inputfile").click();
    };

    $scope.getFile = function(){
        fileReader.readAsDataUrl($scope.file, $scope)
            .then(function(result) {
              $scope.imageSrc = result;
        });

        $scope.carouselshow = false;

    }

    $scope.deletePic = function(id){
        slides.splice(id,1);
        var length = slides.length;
        for (var i = 0; i < length; i++) {
            if(slides[i].index == 0){
                slides[i].active = 'active';
            }

            if(slides[i].index != i){
                slides[i].index = i;
            }
        };
    }
})  

.controller('helpController', function($scope){
    var helpinfo = $scope.helpinfo = [];
    var information = [];
    information[0] = '1. 发布文章时，markdown只识别全角模式的空格，两个换行字符为换行，一个换行字符或多个半角模式下的空格为一个空格';
    information[1] = '2. 用户信息管理包含了所有的用户信息，管理员可以根据用户的某一个信息查询此用户所有的信息或包含此信息的所有用户，并可以对用户的信息进行修改';
    information[2] = '3. 管理员信息管理包含了所有的管理员信息，管理员可以根据查询管理员信息，并对管理员的信息进行修改'
    information[3] = '4. 首页内容管理可以发布新闻以及上传并删除轮播图图片'
    information[4] = '5. 我的账户管理可以修改账户密码'
    information.forEach(function(e){
        helpinfo.push({
            content:e
        });    
    });
    
});  








/************************************************************************************************
 * 临时开发中所用到的数据，为全局共享
 */

var globalData = {};



// 用户类型
globalData.userTypeList = [{
        id: 1,
        name: '大众用户A类'
    }, {
        id: 3,
        name: 'B类'
    }, {
        id: 2,
        name: 'C类'
    }];

// 登陆日志数据，来自公务车管理系统
globalData.signInLogs = [
    {"id":"3","cell":{"logId":3,"sessionId":"2B0D8E7A149522E5131B67F1B9FF5228","userName":"admin","roleId":1,"ip":"127.0.0.1","loginTime":"2015-06-23 13:53:14","logoutTime":"2015-06-23 13:53:30","roleName":"超级管理员"}},
    {"id":"4","cell":{"logId":4,"sessionId":"9C2335F3C41EE17BAA3F6F4972683808","userName":"admin","roleId":1,"ip":"127.0.0.1","loginTime":"2015-06-23 13:53:46","logoutTime":"2015-06-23 15:16:40","roleName":"超级管理员"}},
    {"id":"5","cell":{"logId":5,"sessionId":"80F0EF57CA79BA40FD6C5AAB1E2B7D26","userName":"admin","roleId":1,"ip":"127.0.0.1","loginTime":"2015-06-23 15:07:54","logoutTime":"2015-06-23 15:21:07","roleName":"超级管理员"}},
    {"id":"6","cell":{"logId":6,"sessionId":"BF0216AB685708ADAB9A1EEBAABEBCDA","userName":"admin","roleId":1,"ip":"127.0.0.1","loginTime":"2015-06-23 15:21:07","logoutTime":"2015-06-23 15:51:07","roleName":"超级管理员"}},
    {"id":"7","cell":{"logId":7,"sessionId":"D3F1385D16EB71720F9E48DE88F8A67B","userName":"admin","roleId":1,"ip":"127.0.0.1","loginTime":"2015-06-24 09:28:15","logoutTime":"2015-06-24 09:32:36","roleName":"超级管理员"}},
];

// 权限列表
globalData.authorities = [{
    name: '普通管理员',
    typecode: 0
}, {
    name: '超级管理员',
    typecode: 1
}];

